
package org.winexpress

import org.codehaus.groovy.grails.web.json.JSONObject;
import org.codehaus.groovy.grails.web.json.JSONArray;
import grails.converters.JSON

/**
 *
 * @author Swee Zhi
 */
class ProductManagement {
    
    def listProducts() {
        def products = Product.list()
        JSONArray arr = new JSONArray()
        products.each() {
            JSONObject obj = new JSONObject()
            obj.put("id",it.id)
            obj.put("name",it.name)
            obj.put("description",it.description)
            arr.add(obj)
        }
        
        return arr
    }
    
    def getProductByID(id) {
        def product = Product.findById(id)
        JSONObject obj = new JSONObject()
        obj.put("id",product.id)
        obj.put("name",product.name)
        obj.put("description",product.description)
        
        return obj
    }
    
//    def getProductByName(name) {
//        def Product = Product.findByname(name)
//        JSONObject obj = new JSONObject()
//        obj.put("id",it.id)
//        obj.put("name",it.name)
//        obj.put("description",it.description)
//        
//        return obj
//    }
    
    def addProduct(o) {
        def status
        
        Product p = new Product()
        p.name = o.get("name")
        p.description = o.get("description")
        if (p.save()) {
            status = true
        }
        else {
            status = false
        }        
        println 'Management >> Add Wine >> ' + status
        
        return status
    }
    
    def updateProduct(product) {
        def status
        
        Product p = Product.findById(product.id)
        if (product.has("name")) { p.name = product.name }
        if (product.has("description")) { p.description = product.description }
        if (p.save(flush:true)) {
            status = true
        }
        else {
            status = false
        }        
        println 'Management >> Update Wine >> ' + status
        
        return status
    }
    
    def deleteProduct(id) {
        def status
        
        Product p = Product.findById(id)
        if (p.delete()) {
            status = true
        }
        else {
            status = false
        }        
        println 'Management >> Delete Wine >> ' + status
        
        return status
    }
	
}

